using UnityEngine;
using System.Collections;

public class mcCamera2DScrollH : MonoBehaviour
{
	public Vector3 cameraPosition;
	public float moveSpeed;
	
	protected bool mouseDown;
	
	// Use this for initialization
	void Start()
	{
		this.moveSpeed = 0.5f;
		this.mouseDown = false;
	}
	
	// Update is called once per frame
	void Update()
	{
		this.MoveFromMouse();
		this.MoveFromKeyboard();	
	}
	
	void MoveFromMouse()
	{
		GameObject player = GameObject.FindWithTag("Player");
		if(player == null)
			return;
		
		if(Input.GetMouseButtonDown(0) == true)
		{
			Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
			this.cameraPosition.x = ray.origin.x;
			this.mouseDown = true;
		}
		else if(Input.GetMouseButtonUp(0) == true)
		{
			this.mouseDown = false;
			return;
		}
		
		if(Input.GetMouseButton(0) == false)
			return;
		
		Ray newRay = Camera.main.ScreenPointToRay(Input.mousePosition);
		if(newRay.origin.x == this.cameraPosition.x)
			return;

		float newPos = -(float)((newRay.origin.x - this.cameraPosition.x) * this.moveSpeed);
		Debug.Log("Offset: " + newPos);
		player.transform.Translate(newPos, 0, 0, player.transform);
		this.transform.Translate(newPos, 0, 0, Camera.main.transform);
		
		this.cameraPosition.x = newRay.origin.x;
	}
	
	void MoveFromKeyboard()
	{
		GameObject player = GameObject.FindWithTag("Player");
		if(player == null)
			return;
		
		if(Input.GetKey(KeyCode.LeftArrow) == true)
		{
			this.transform.Translate(-Time.deltaTime, 0, 0, Camera.main.transform);
			if(player != null)
			{
				player.transform.Translate(-Time.deltaTime, 0, 0, player.transform);
			}
		}
		else if(Input.GetKey(KeyCode.RightArrow) == true)
		{
			this.transform.Translate(Time.deltaTime, 0, 0, Camera.main.transform);
			if(player != null)
			{
				player.transform.Translate(Time.deltaTime, 0, 0, player.transform);
			}
		}
	}
}
